<template>
  <a-drawer
    title="客户指定分类"
    width="90%"
    :visible="visible"
    @close="
      () => {
        this.visible = false
        this.parentObj.getDataList()
      }
    "
  >
    <a-row :gutter="5">
      <a-col :span="12">
        <a-card
          :bordered="false"
          title="全部客户列表"
          :hoverable="true"
          :headStyle="{ color: '#fff', fontSize: '18px', fontweight: 'bolder', backgroundColor: '#1890FF' }"
          style="width: 100%;padding: 0;margin: 0 auto"
        >
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="5">
                <a-col :span="5">
                  <a-form-item>
                    <a-input @keydown="inputKeyDownleft" v-model="queryParamleft.Conditions[0].Keyword" placeholder="客户名称" />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-button
                    type="primary"
                    @click="
                      () => {
                        this.paginationleft.current = 1
                        this.getDataListleft()
                      }
                    "
                  >查询
                  </a-button>
                  <a-button style="margin-left: 5px" @click="Repossessleft">重置</a-button>
                </a-col>
                <a-col :span="10">
                  <a-radio-group
                    v-model="queryParamleft.Conditions[1].keyword"
                    :default-value="null"
                    button-style="solid"
                    @change="cCusTypeChangeleft"
                  >
                    <a-radio-button :value="null"> 全部</a-radio-button>
                    <a-radio-button :value="1"> 正式</a-radio-button>
                    <a-radio-button :value="0"> 潜在</a-radio-button>
                    <a-radio-button :value="2"> 休眠</a-radio-button>
                    <a-radio-button :value="3"> 待转正</a-radio-button>
                  </a-radio-group>
                </a-col>
                <a-col :span="4" style="text-align: right">
                  <a-button
                    type="primary"
                    icon="login"
                    @click="handleClassleft(selectedRowKeysleft)"
                    :disabled="!hasSelectedleft()"
                    :loading="btnLoadingleft"
                  >一键分类
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-table
            ref="lefttable"
            :scroll="{ y: tableHeight }"
            :columns="columns"
            :rowKey="(row, index) => row.Id"
            :dataSource="CustListleft"
            :pagination="paginationleft"
            :loading="loadingleft"
            @change="handleTableChangeleft"
            :rowSelection="{ selectedRowKeys: selectedRowKeysleft, onChange: onSelectChangeleft, type: 'checkbox' }"
            :bordered="true"
            size="small"
            :customRow="loadRowleft"
          >
            <template slot="cCusType" slot-scope="text, record">
              <a-tag v-if="record.cCusType === 0" color="blue">潜在</a-tag>
              <a-tag v-else-if="record.cCusType === 1" color="green">正式</a-tag>
              <a-tag v-else-if="record.cCusType === 2" color="red">休眠</a-tag>
              <a-tag v-else-if="record.cCusType === 3" color="orange">待转正</a-tag>
            </template>
          </a-table>
        </a-card>
      </a-col>
      <a-col :span="12">
        <a-card
          id="rightCard"
          :bordered="false"
          :title="GetClassName"
          :hoverable="true"
          :headStyle="{ color: '#fff', fontSize: '18px', fontweight: 'bold', backgroundColor: '#1890FF' }"
          style="width: 100%;padding: 0;margin: 0 auto"
        >
          <a-button
            slot="extra"
            type="text"
            icon="delete"
            @click="handleClassrightclear()"
            :loading="btnLoadingrightclear"
          >一键清空
          </a-button>
          <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="5">
                <a-col :span="5">
                  <a-form-item>
                    <a-input
                      @keydown="inputKeyDownright"
                      v-model="queryParamright.Conditions[0].Keyword"
                      placeholder="客户名称"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="5">
                  <a-button
                    type="primary"
                    @click="
                      () => {
                        this.paginationright.current = 1
                        this.getDataListright()
                      }
                    "
                  >查询
                  </a-button>
                  <a-button style="margin-left: 5px" @click="Repossessright">重置</a-button>
                </a-col>
                <a-col :span="10">
                  <a-radio-group
                    v-model="queryParamright.Conditions[1].keyword"
                    :default-value="null"
                    button-style="solid"
                    @change="cCusTypeChangeright"
                  >
                    <a-radio-button :value="null"> 全部</a-radio-button>
                    <a-radio-button :value="1"> 正式</a-radio-button>
                    <a-radio-button :value="0"> 潜在</a-radio-button>
                    <a-radio-button :value="2"> 休眠</a-radio-button>
                    <a-radio-button :value="3"> 待转正</a-radio-button>
                  </a-radio-group>
                </a-col>
                <a-col :span="4" style="text-align: right">
                  <a-button
                    type="primary"
                    icon="logout"
                    @click="handleClassright(selectedRowKeysright)"
                    :disabled="!hasSelectedright()"
                    :loading="btnLoadingright"
                  >一键移出
                  </a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-table
            ref="righttable"
            :scroll="{ y: tableHeight }"
            :columns="columns"
            :rowKey="(row, index) => row.Id"
            :dataSource="CustListright"
            :pagination="paginationright"
            :loading="loadingright"
            @change="handleTableChangeright"
            :rowSelection="{ selectedRowKeys: selectedRowKeysright, onChange: onSelectChangeright, type: 'checkbox' }"
            :bordered="true"
            size="small"
            :customRow="loadRowright"
          >
            <template slot="cCusType" slot-scope="text, record">
              <a-tag v-if="record.cCusType === 0" color="blue">潜在</a-tag>
              <a-tag v-else-if="record.cCusType === 1" color="green">正式</a-tag>
              <a-tag v-else-if="record.cCusType === 2" color="red">休眠</a-tag>
              <a-tag v-else-if="record.cCusType === 3" color="orange">待转正</a-tag>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </a-drawer>
</template>

<script>
const columns = [
  { title: '编码', dataIndex: 'cCusCode', align: 'left', width: '20%' },
  { title: '名称', dataIndex: 'cCusName', align: 'left', width: '45%' },
  {
    title: '类型',
    dataIndex: 'cCusType',
    align: 'center',
    width: '10%',
    scopedSlots: { customRender: 'cCusType' }
  },
  {
    title: '分组',
    dataIndex: 'GroupName',
    align: 'center',
    customRender: (value, row) => {
      if (row.GroupName != null && row.GroupName.length > 0) {
        return row.GroupName
      } else {
        return '无'
      }
    },
    width: '15%'
  }
]
export default {
  name: 'GroupTable',
  props: {
    parentObj: Object
  },
  data () {
    return {
      visible: false, // 页面状态
      tableHeight: 570, // 表格高度
      ClassName: '', // 客户分类名称
      ClassId: '', // 客户分类ID
      CustListleft: [], // 左侧全部未分类客户数据集
      CustListright: [], // 右侧分配当前类客户数据集
      loadingleft: false, // 左侧列表加载
      btnLoadingleft: false, // 左侧 一键分类 加载
      btnLoadingright: false, // 右侧 取消分类
      btnLoadingrightclear: false, // 右侧 清空类中客户
      loadingright: false, // 右侧列表加载
      columns, // 左右公用标题集合
      paginationleft: {
        // 左侧分页对象信息
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      paginationright: {
        // 右侧分页对象信息
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      },
      queryParamleft: {
        // 右侧查询条件对象集合
        ClassId: this.ClassId,
        IsIN: false,
        Conditions: [
          { Condition: 'cCusName' },
          { Condition: 'cCusType', keyword: null }
        ]
      },
      queryParamright: {
        // 右侧查询条件对象集合
        ClassId: this.ClassId,
        IsIN: true,
        Conditions: [
          { Condition: 'cCusName' },
          { Condition: 'cCusType', keyword: null }
        ]
      },
      filtersleft: {}, // 左侧分页过滤
      filtersright: {}, // 右侧分页过滤
      sorterleft: { field: 'Id', order: 'desc' }, // 左侧排序条件
      sorterright: { field: 'Id', order: 'desc' }, // 右侧排序条件
      selectedRowsleft: [], // 左侧选中行
      selectedRowsright: [], // 右侧选中行
      selectedRowKeysleft: [], // 左侧选中客户对象键 集合
      selectedRowKeysright: [] // 右侧选中客户对象键 集合
    }
  },
  mounted () {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      this.tableHeight = this.getTableHeight(true)
    })
  },
  methods: {
    // 初始化信息
    init () {
      this.paginationleft = {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      }
      this.paginationright = {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true
      }
      // 获取客户分类信息
      this.ClassId = ''
      this.ClassName = ''
    },

    // 页面打开方法
    openForm (row) {
      this.init()
      this.visible = true
      this.ClassName = row.ClassName
      this.ClassId = row.Id
      this.Repossessleft()
      this.Repossessright()
    },
    // 拼接分组信息
    GetClassName () {
      return '当前：【' + this.ClassName + '】的客户列表'
    },

    // 左侧表格分页操作
    handleTableChangeleft (pagination, filters, sorter) {
      this.paginationleft = { ...pagination }
      this.filtersleft = { ...filters }
      this.sorterleft = { ...sorter }
      this.getDataListleft()
    },

    // 右侧表格分页操作
    handleTableChangeright (pagination, filters, sorter) {
      this.paginationright = { ...pagination }
      this.filtersright = { ...filters }
      this.sorterright = { ...sorter }
      this.getDataListright()
    },

    // 左侧条件框输入 回车查询
    inputKeyDownleft (e) {
      if (e.keyCode === 13) {
        this.getDataListleft()
      }
    },

    // 右侧条件输入 回车查询
    inputKeyDownright (e) {
      if (e.keyCode === 13) {
        this.getDataListright()
      }
    },

    // 左侧重置按钮
    Repossessleft () {
      this.queryParamleft = {
        // 右侧查询条件对象集合
        ClassId: this.ClassId,
        IsIN: false,
        Conditions: [
          { Condition: 'cCusName' },
          { Condition: 'cCusType', keyword: null }
        ]
      }
      this.getDataListleft()
    },

    // 右侧重置按钮
    Repossessright () {
      this.queryParamright = {
        // 右侧查询条件对象集合
        ClassId: this.ClassId,
        IsIN: true,
        Conditions: [
          { Condition: 'cCusName' },
          { Condition: 'cCusType', keyword: null }
        ]
      }
      this.getDataListright()
    },

    // 左侧选中客户添加到客户选中集合
    onSelectChangeleft (selectedRowKeys, selectedRows) {
      this.selectedRowKeysleft = selectedRowKeys
      this.selectedRowsleft = selectedRows
    },

    // 右侧选中客户添加到客户选中集合
    onSelectChangeright (selectedRowKeys, selectedRows) {
      this.selectedRowKeysright = selectedRowKeys
      this.selectedRowsright = selectedRows
    },

    // 一键将左侧选中客户分配至当前组
    handleClassleft (ids) {
      // 打开按钮加载
      this.btnLoadingleft = true
      // 打开列表加载
      this.loadingleft = true
      // 判断分组的ID是否丢失
      if (!this.ClassId) return this.$message.error('请选择分类')
      // 初始化传入参数实体
      const entityData = {}
      entityData.ClassId = this.ClassId
      entityData.ClassName = this.ClassName
      entityData.CustIdsList = ids
      // 调用保存接口 保存分组数据
      this.$http.post('/CustomerManagement/CustomerClassAllocation/SaveDataForAdd', entityData).then(resJson => {
        if (resJson.Success) {
          this.$message.success('添加成功!')
          this.loadingleft = false
          this.btnLoadingleft = false
          this.getDataListleft() // 刷新左侧列表
          this.getDataListright() // 刷新右侧列表
        } else {
          this.$message.error(resJson.Msg)
        }
        setTimeout(() => {
          this.btnLoadingleft = false
          this.loadingleft = false
        }, 500)
      })
    },

    // 判断左侧是否选中客户
    hasSelectedleft () {
      return this.selectedRowKeysleft.length > 0
    },

    // 一键将右侧选中客户移出当前组
    handleClassright (ids) {
      // 声明当年页面对象
      const thisObj = this
      // 弹出确认对话框
      this.$confirm({
        title: '确认移出当前选中客户吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            // 打开按钮加载
            thisObj.btnLoadingright = true
            // 打开列表加载
            thisObj.loadingright = true
            // 判断分组的ID是否丢失
            if (!thisObj.ClassId) return thisObj.$message.error('请选择分类')
            // 初始化传入参数实体
            const entityData = {}
            entityData.ClassId = thisObj.ClassId
            entityData.ClassName = thisObj.ClassName
            entityData.CustIdsList = ids
            // 调用保存接口 保存分组数据
            thisObj.$http
              .post('/CustomerManagement/CustomerClassAllocation/SaveDataForRemove', entityData)
              .then(resJson => {
                thisObj.btnLoadingright = false
                thisObj.loadingright = false
                resolve()
                if (resJson.Success) {
                  thisObj.$message.success('移除成功!')
                  thisObj.getDataListleft() // 刷新左侧列表
                  thisObj.getDataListright() // 刷新右侧列表
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
                setTimeout(() => {
                  thisObj.btnLoadingleft = false
                }, 500)
              })
          })
        }
      })
    },

    // 判断右侧是否选中客户
    hasSelectedright () {
      return this.selectedRowKeysright.length > 0
    },

    // 一键将右侧客户全部清空至无分组状态
    handleClassrightclear () {
      // 声明当年页面对象
      const thisObj = this
      // 弹出确认对话框
      this.$confirm({
        title: '确认清空当前分类的所有客户吗?',
        onOk () {
          return new Promise((resolve, reject) => {
            // 打开按钮加载
            thisObj.btnLoadingright = true
            // 打开列表加载
            thisObj.loadingright = true
            // 判断分组的ID是否丢失
            if (!thisObj.ClassId) return thisObj.$message.error('请选择分类')
            // 初始化传入参数实体
            const entityData = {}
            entityData.ClassId = thisObj.ClassId
            entityData.ClassName = thisObj.ClassName
            entityData.CustIdsList = null
            // 调用保存接口 保存分组数据
            thisObj.$http
              .post('/CustomerManagement/CustomerClassAllocation/SaveDataForClear', entityData)
              .then(resJson => {
                thisObj.btnLoadingright = false
                thisObj.loadingright = false
                resolve()
                if (resJson.Success) {
                  thisObj.$message.success('清空成功!')
                  thisObj.getDataListleft() // 刷新左侧列表
                  thisObj.getDataListright() // 刷新右侧列表
                } else {
                  thisObj.$message.error(resJson.Msg)
                }
                setTimeout(() => {
                  thisObj.btnLoadingleft = false
                }, 500)
              })
          })
        }
      })
    },

    // 左侧筛选客户类型
    cCusTypeChangeleft () {
      this.getDataListleft()
    },

    // 右侧筛选客户类型
    cCusTypeChangeright () {
      this.getDataListright()
    },

    // 获取左侧列表全部未分类客户列表
    getDataListleft () {
      this.selectedRowKeysleft = []
      this.loadingleft = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMoreConditionOfClass', {
          PageIndex: this.paginationleft.current,
          PageRows: this.paginationleft.pageSize,
          SortField: this.sorterleft.field || 'Id',
          SortType: this.sorterleft.order,
          Search: this.queryParamleft,
          ...this.filtersleft
        })
        .then(resJson => {
          this.loadingleft = false
          this.CustListleft = resJson.Data
          if (this.CustListleft) {
            const pagination = { ...this.paginationleft }
            pagination.total = resJson.Total
            this.paginationleft = pagination
          }
        })
    },

    // 获取右侧分配当前分类的客户列表
    getDataListright () {
      this.selectedRowKeysright = []
      this.loadingright = true
      this.$http
        .post('/CustomerManagement/CustomerInfo/GetDataListByMoreConditionOfClass', {
          PageIndex: this.paginationright.current,
          PageRows: this.paginationright.pageSize,
          SortField: this.sorterright.field || 'Id',
          SortType: this.sorterright.order,
          Search: this.queryParamright,
          ...this.filtersright
        })
        .then(resJson => {
          this.loadingright = false
          this.CustListright = resJson.Data
          if (this.CustListright) {
            const pagination = { ...this.paginationright }
            pagination.total = resJson.Total
            this.paginationright = pagination
          }
        })
    },

    // 左侧表格行操作
    loadRowleft (record, index) {
      return {
        on: {
          click: () => {
            // 记录为disabled则直接返回，默认为不可选
            if (record.disabled) return
            const type = 'checkbox'
            const key = record.Id || index
            let selectedRows = this.selectedRowsleft
            let selectedRowKeys = this.selectedRowKeysleft
            if (type === 'radio') {
              selectedRowKeys = [key]
              selectedRows = [record]
            }
            if (!this.selectedRowKeysleft.includes(key)) {
              selectedRowKeys.push(key)
              selectedRows.push(record)
            } else {
              const index = this.selectedRowKeysleft.findIndex(skey => skey === key)
              selectedRows.splice(index, 1)
              selectedRowKeys.splice(index, 1)
            }

            this.updateSelectleft(selectedRowKeys, selectedRows)
            this.onSelectChangeleft(selectedRowKeys, selectedRows)
          }
        }
      }
    },

    // 右侧表格行操作
    loadRowright (record, index) {
      return {
        on: {
          click: () => {
            // 记录为disabled则直接返回，默认为不可选
            if (record.disabled) return
            const type = 'checkbox'
            const key = record.Id || index
            let selectedRows = this.selectedRowsright
            let selectedRowKeys = this.selectedRowKeysright
            if (type === 'radio') {
              selectedRowKeys = [key]
              selectedRows = [record]
            }
            if (!this.selectedRowKeysright.includes(key)) {
              selectedRowKeys.push(key)
              selectedRows.push(record)
            } else {
              const index = this.selectedRowKeysright.findIndex(skey => skey === key)
              selectedRows.splice(index, 1)
              selectedRowKeys.splice(index, 1)
            }

            this.updateSelectright(selectedRowKeys, selectedRows)
            this.onSelectChangeright(selectedRowKeys, selectedRows)
          }
        }
      }
    },

    // 左侧选中行更新
    updateSelectleft (selectedRowKeys, selectedRows) {
      this.selectedRowsleft = selectedRows
      this.selectedRowKeysleft = selectedRowKeys
    },

    // 右侧选中行更新
    updateSelectright (selectedRowKeys, selectedRows) {
      this.selectedRowsright = selectedRows
      this.selectedRowKeysright = selectedRowKeys
    }

  }
}
</script>

<style scoped lang="less">
/deep/ #rightCard .ant-card-extra{
  padding: 0;
}
</style>
